package com.gitee.loyo.jdbc

import com.gitee.loyo.KSQL
import kotlin.reflect.KClass

fun interface PageQuery<T>{

    fun limit(offset: Int, limit: Int): Pair<Int, List<T>>

    companion object{

        fun <T: Any> query(conn: Conn, type:KClass<T>, opt: StmtOptions, sql: String, vararg args: Any?) = PageQuery { offset, limit ->
                val executeOnce = conn.executeOnce
                conn.executeOnce = false
                val count = conn.query(opt, "select count(*) from ($sql) tmp", *args).asInt()
                if(count == 0){
                    if(executeOnce){
                        conn.executeOnce = executeOnce
                        conn.close()
                    }
                    count to emptyList()
                }else{
                    conn.executeOnce = executeOnce
                    val list = when(KSQL.dialect){
                        com.gitee.loyo.Dialect.Mysql -> conn.query(opt, "select * from ($sql) tmp limit $offset, $limit", *args).asList(type)
                        com.gitee.loyo.Dialect.Postgresql -> conn.query(opt, "select * from ($sql) tmp limit $limit offset $offset", *args).asList(type)
                    }
                    count to list
                }
            }

    }
}